package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.PurchaseRefundAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.StoreRetreatOrderBean;
import com.example.sunmiv1.entity.StoreWarehouseInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//  採購管理.採購退貨
public class PurchaseRefundActivity extends BaseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.spinner_warehouse_choose)
    Spinner sprWarehouseChoose;
    @BindView(R.id.spinner_supplies)
    Spinner sprSupplies;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.ed_order_num_search)
    EditText edOrderNumSearch;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.purchaseOrder_add)
    Button purchaseOrderAdd;
    @BindView(R.id.ed_start_time)
    TextView edStartTime;
    @BindView(R.id.ed_end_time)
    TextView edEndTime;
    @BindView(R.id.rv_refund_orders)
    RecyclerView rvRefundOrders;

    private static final int GET_ERROR_STATUS = 0x01;
    private static final int GET_INFO_STOREWAREHOUSE = 0x02;
    private static final int GET_PRLIST = 0x03;
    private static final int GET_PRLIST_02 = 0x04;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;


    private LoadingDialog loadingDialog;
    private StoreWarehouseInfo storeWarehouseInfo;// 採購倉與供貨商信息 Bean
    private StoreRetreatOrderBean mStoreRetreatOrderBean; // 退貨訂單Bean

    private ACache aCache;// 緩存

    /* id列表和名稱以  0<-->1 到size()<-->size()+1一對一映射 */
    private List<String> sprWarehouseIdList;    //倉庫id列表
    private List<String> sprWarehouseNameList; // 倉庫名稱列表（左上角spinner）
    private List<String> sprSupplierIdList;    // 供貨商id列表
    private List<String> sprSupplierNameList;  // 供貨商名稱列表（右上角spinner）

    private List<StoreRetreatOrderBean.DataBean> mPurchaseRefundList = new ArrayList<>();

    private ArrayAdapter wSpinnerAdapter; // 倉庫列表spinner適配器
    private ArrayAdapter sSpinnerAdapter; // 供貨商列表spinner適配器
    private PurchaseRefundAdapter mPurchaseRefundAdapter;

    /* */
    private String mWarehouseId;//spinner中選擇的倉庫
    private String mSupplierId;//spinner中選擇的供應商
    private String orderNum;//R.id.ed_order_num_search獲取的訂單號
    private int page;
    private int limit;

    private String userType;// 用戶身份

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_INFO_STOREWAREHOUSE:
                    wSpinnerAdapter.notifyDataSetChanged();
                    sSpinnerAdapter.notifyDataSetChanged();
                    break;
                case GET_PRLIST:
                    mPurchaseRefundAdapter.notifyDataSetChanged();
                    break;
                case GET_PRLIST_02:
                    mPurchaseRefundAdapter.notifyDataSetChanged();
//                    mPurchaseRefundAdapter.notifyItemRangeInserted(20, mPurchaseRefundList.size() - 20);
                    break;
                case GET_ERROR_STATUS:
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        setContentView(R.layout.activity_purchase_refund);
        ButterKnife.bind(this);
        loadingDialog = new LoadingDialog(this);
        titleTitle.setText(R.string.purchaseRefundTitle);
        aCache = ACache.get(this);
        userType = aCache.getAsString("userType");
        mWarehouseId = null;//spinner中選擇的倉庫
        mSupplierId = null;//spinner中選擇的供應商
        orderNum = null;//R.id.ed_order_num_search獲取的訂單號
        getSupplierAndWarehouseInfo();
        getStoreRetreatOrder();
        initSpinner();
        mPurchaseRefundAdapter = new PurchaseRefundAdapter(this, mPurchaseRefundList);
        rvRefundOrders.setLayoutManager(new LinearLayoutManager(this));
        rvRefundOrders.setAdapter(mPurchaseRefundAdapter);
        LogUtil.i("(1)mPurchaseRefundList:" + mPurchaseRefundList.size());
    }

    @Override
    protected void initData() {
    }



    // 初始化spinner
    private void initSpinner() {
        sprWarehouseNameList = new ArrayList<>();
        sprWarehouseIdList = new ArrayList<>();
        sprWarehouseNameList.add("所有倉庫");
        sprWarehouseNameList.add("暫無倉庫");
        sprSupplierNameList = new ArrayList<>();
        sprSupplierIdList = new ArrayList<>();
        sprSupplierNameList.add("所有供貨商");
        sprSupplierNameList.add("暫無供貨商");
        wSpinnerAdapter = new ArrayAdapter(this, R.layout.item_drop, sprWarehouseNameList);
        wSpinnerAdapter.setDropDownViewResource(R.layout.item_drops);
        sprWarehouseChoose.setAdapter(wSpinnerAdapter);
        sSpinnerAdapter = new ArrayAdapter(this, R.layout.item_drop, sprSupplierNameList);
        sSpinnerAdapter.setDropDownViewResource(R.layout.item_drops);
        sprSupplies.setAdapter(sSpinnerAdapter);
    }




    /**
     * 普通點擊事件
     *
     * @param view
     */
    @OnClick({R.id.ed_start_time, R.id.ed_end_time, R.id.title_back, R.id.iv_search, R.id.purchaseOrder_add,R.id.btn_to_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.iv_search:
                edOrderNumSearch.setCursorVisible(false);
                getStoreRetreatOrder();
                break;
            case R.id.purchaseOrder_add:
                edOrderNumSearch.setCursorVisible(false);
                Intent intent = new Intent(this, PurchaseRefundAddingActivity.class);
                startActivityForResult(intent,42);
                break;
            case R.id.ed_start_time:
                edOrderNumSearch.setCursorVisible(false);
                getDateFromDatePickerDialog(edStartTime);
                getStoreRetreatOrder();
                break;
            case R.id.ed_end_time:
                edOrderNumSearch.setCursorVisible(false);
                getDateFromDatePickerDialog(edEndTime);
                getStoreRetreatOrder();
                break;
            case R.id.btn_to_top:
                rvRefundOrders.smoothScrollToPosition(0);
                break;
        }
    }

    /**
     * 初始化spinner和PullToRefreshListView 等控件監聽
     */
    @Override
    protected void initListener() {
        sprSupplies.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /**
             * @param parent   該spinner的adapter
             * @param view     adapter中的一個item
             * @param position The position of the view in the adapter
             * @param id       The row id of the item that is selected
             */
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    mSupplierId = null;
                } else {
                    mSupplierId = sprSupplierIdList.get(position - 1);
                }
                getStoreRetreatOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sprWarehouseChoose.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                LogUtil.i("spinner顯示：" + sprWarehouseChoose.getSelectedItem());
                if (position == 0) {
                    mWarehouseId = null;
                } else {
                    mWarehouseId = sprWarehouseIdList.get(position - 1);
                }
                getStoreRetreatOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mPurchaseRefundAdapter.setItemDetailClickListener(new PurchaseRefundAdapter.ItemDetailClickListener() {
            @Override
            public void onItemDetailClick(int position) {
                Intent intent = new Intent(PurchaseRefundActivity.this, PurchaseRefundDetailsActivity.class);
                intent.putExtra("orderId", mPurchaseRefundList.get(position).getId());
                startActivity(intent);
            }
        });
        edOrderNumSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                orderNum = s.toString();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK) {
            switch (requestCode) {
                case 42:
                    if(data.getBooleanExtra("refresh",true))
                    getStoreRetreatOrder();
                    break;
            }
        }
    }

    /**
     * 網絡加載退貨列表  （先記載部分信息，剩下的在getStoreRetreatOrder()裏面加載）
     * String orderNumber, int warehouseId, int supplierId, int page, int limit, String startTime, String endTime
     * String warehouseId,String supplierId
     */
    private void getStoreRetreatOrder() {
//        mWarehouseId ;//spinner中選擇的倉庫
//        mSupplierId  ;//spinner中選擇的供應商
//        startTime  ;//R.id.ed_start_time獲取的時間
//        endTime   ;//R.id.ed_end_time獲取的時間
//        orderNum   ;//R.id.ed_order_num_search獲取的訂單號
        String url = "";
        if (userType.equals("1")) {
            url = Common.ORDER_STORE_RETREAT_1;
        } else if (userType.equals("2")) {
            url = Common.ORDER_STORE_RETREAT_2;
        }
        page = 1;
        limit = 4;
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("warehouse_id", mWarehouseId);
            jsonObject.put("supplier_id", mSupplierId);
            jsonObject.put("order_number", orderNum);
            jsonObject.put("page", "1");
            jsonObject.put("limit", "20");
            jsonObject.put("start_time", edStartTime.getText().toString().trim());
            jsonObject.put("end_time", edEndTime.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, url, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                mPurchaseRefundList.clear();
                mStoreRetreatOrderBean = GsonUtils.JsonToBean(text, StoreRetreatOrderBean.class);
                if (mStoreRetreatOrderBean.getStatus() == 1) {
                    mPurchaseRefundList.clear();
                    mPurchaseRefundList.addAll(mStoreRetreatOrderBean.getData());
                    mHandler.sendEmptyMessage(GET_PRLIST);
                    if (mPurchaseRefundList.size() == 20)
                        getStoreRetreatOrder2();
                } else {
                    Toast.makeText(PurchaseRefundActivity.this, "暫無相關信息", Toast.LENGTH_SHORT).show();
                }
                loadingDialog.dismiss();
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });

    }

    // 繼續加載剩下的信息
    private void getStoreRetreatOrder2() {
        String url = "";
        if (userType.equals("1")) {
            url = Common.ORDER_STORE_RETREAT_1;
        } else if (userType.equals("2")) {
            url = Common.ORDER_STORE_RETREAT_2;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("warehouse_id", mWarehouseId);
            jsonObject.put("supplier_id", mSupplierId);
            jsonObject.put("order_number", orderNum);
//            jsonObject.put("page", "");
//            jsonObject.put("limit", "");
            jsonObject.put("start_time", edStartTime.getText().toString().trim());
            jsonObject.put("end_time", edEndTime.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, url, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                mStoreRetreatOrderBean = GsonUtils.JsonToBean(text, StoreRetreatOrderBean.class);
                if (mStoreRetreatOrderBean.getStatus() == 1) {
                    mPurchaseRefundList.addAll(mStoreRetreatOrderBean.getData().subList(20, mStoreRetreatOrderBean.getData().size()));
                    mHandler.sendEmptyMessage(GET_PRLIST_02);
                } else {
                    Toast.makeText(PurchaseRefundActivity.this, "暫無相關信息", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });
    }


    /**
     * 獲取採購倉與供貨商信息
     */
    private void getSupplierAndWarehouseInfo() {
        String url = "";
        if (userType.equals("1")) {
            url = Common.INFO_STORE_AND_WAREHOUSE_1;
        } else if (userType.equals("2")) {
            url = Common.INFO_STORE_AND_WAREHOUSE_2;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, url, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                storeWarehouseInfo = GsonUtils.JsonToBean(text, StoreWarehouseInfo.class);
                if (storeWarehouseInfo.getStatus() == 1) {
                    mHandler.sendEmptyMessage(GET_INFO_STOREWAREHOUSE);
                    if (sprSupplierNameList.size() == 2)
                        sprSupplierNameList.remove(1);
                    for (int i = 0; i < storeWarehouseInfo.getSupplierList().size(); i++) {
                        sprSupplierIdList.add(storeWarehouseInfo.getSupplierList().get(i).getId());
                        sprSupplierNameList.add(storeWarehouseInfo.getSupplierList().get(i).getSupplier_name());
                    }

                    if (sprWarehouseNameList.size() == 2)
                        sprWarehouseNameList.remove(1);
                    for (int i = 0; i < storeWarehouseInfo.getWarehouseList().size(); i++) {
                        sprWarehouseIdList.add(storeWarehouseInfo.getWarehouseList().get(i).getId());
                        sprWarehouseNameList.add(storeWarehouseInfo.getWarehouseList().get(i).getName());
                    }
                } else {
                    mHandler.sendEmptyMessage(GET_ERROR_STATUS);
                    Toast.makeText(PurchaseRefundActivity.this, "暫無信息", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
//                    loadingDialog.dismiss();
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }
}
